import type Node from 'element-plus-cisdi/es/components/tree/src/model/node';
import type { DefaultRow, FetchPrams } from '@/types/RoleAuthorization';
import { computed, getCurrentInstance, nextTick, reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { getRoleList, getRoleTreeList } from '@/api/RoleAuthorizationDialog';
import { UserService } from '@/services/UserService';

export function useRole() {
  const { t } = useI18n();
  const orgTreeCode = ref('');
  const orgTreeCodeArray = ref<string[]>([]);
  const initParams = reactive({ value: '', status: true });
  const instance = getCurrentInstance();
  const allTableParams = ref();
  const firstOrgLabel = ref('');
  const currentNodeKey = ref('');
  const column = computed(() => [
    {
      label: t('authorization.roleCode'),
      prop: 'roleCode',
      width: '120',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.roleName'),
      prop: 'roleName',
      width: '120',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.description'),
      prop: 'description',
      width: '200',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.orgLevel'),
      prop: 'orgLevel',
      width: '80',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.inheritedOrgName'),
      prop: 'inheritedRoleName',
      width: '180',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.subVisible'),
      prop: 'subVisible',
      width: '80',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.status'),
      prop: 'status',
      width: '80',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.tip'),
      prop: 'remark',
      width: '200',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.createBy'),
      prop: 'createName',
      width: '120',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.createTime'),
      prop: 'createTime',
      width: '180',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.updateBy'),
      prop: 'updateName',
      width: '120',
      align: 'left',
      showOverflowTooltip: true,
    },
    {
      label: t('authorization.updateTime'),
      prop: 'updateTime',
      width: '180',
      align: 'left',
      showOverflowTooltip: true,
    },
  ]);

  // 获取表格数据
  async function fetchData(params: FetchPrams) {
    allTableParams.value = params;
    orgTreeCode.value = params?.code ?? initParams.value;
    const scope = params.scope === 'HIGH' ? '3' : (params.scope === 'CURRENT' ? '2' : '1');
    const scopeId = scope || '1';
    const paramsTable = { scope: scopeId, orgCode: orgTreeCode.value, current: params?.pageNum, size: params?.pageSize, search: params?.searchKey };
    initParams.status = false;
    return new Promise<{ data: DefaultRow[], total: number }>((resolve, reject) => {
      getRoleList(paramsTable).then((res) => {
        resolve({
          data: res.data.records || [],
          total: Number(res.data.total) || 0,
        });
      }).catch((err) => {
        reject(err);
      });
    });
  }
  // 设置标题的方法
  const setTreeActionTitle = (label: string) => {
    const treeRef = instance?.refs.treeTablePageRef as any;
    if (treeRef?.setActionTitle) {
      treeRef.setActionTitle(label);
    }
  };
  // 设置默认选中的方法
  const setTreeActionKey = (id: string) => {
    const treeRef = instance?.refs.treeTablePageRef as any;
    if (treeRef?.searchTreeRef) {
      treeRef.searchTreeRef?.treeRef?.setCurrentKey?.(id);
    }
  };
  // 设置获取默认数据方法
  const setTreeLoad = () => {
    const treeRef = instance?.refs.treeTablePageRef as any;
    if (treeRef?.loadData) {
      treeRef?.loadData?.({ code: initParams.value });
    }
  };
  // 获取左侧树
  async function requestTreeData(node?: Node, resolve?: (data: any[]) => void) {
    try {
      const res = await getRoleTreeList({
        orgCode: node?.data?.code || 'root',
        isTree: '1',
        loadType: 0,
      });

      if (initParams.status) {
        orgTreeCode.value = res.data?.root[0]?.code;
        initParams.value = res.data?.root[0]?.code;
        orgTreeCodeArray.value = [res.data?.root[0]?.code];
        await nextTick();
        setTreeActionTitle(res.data?.root[0]?.label);
        setTreeActionKey(res.data?.root[0]?.code);
        resolve?.(res.data.root || []);
        firstOrgLabel.value = res.data?.root[0]?.label || '';
      } else {
        const dataKey = node?.data?.code || 'root';
        resolve?.(res.data?.[dataKey] || []);
      }
    } catch (error) {
      console.error(error);
      resolve?.([]);
    }
  }

  async function searchData(params: object) {
    const data = {
      orgCode: 'root',
      isTree: 0,
      loadType: 1,
      ...params,
    };
    return UserService.getOrgTreeOriginalData(data);
  }

  function treeClearSearchValue() {
    currentNodeKey.value = initParams.value;
    setTreeActionTitle(firstOrgLabel.value);
    setTreeActionKey(initParams.value);
    setTreeLoad();
  }
  function handleNodeClick(data: any) {
    currentNodeKey.value = data.code;
  }

  return {
    column,
    orgTreeCode,
    orgTreeCodeArray,
    handleNodeClick,
    allTableParams,
    searchData,
    treeClearSearchValue,
    currentNodeKey,
    fetchData,
    requestTreeData,
  };
}
